<template>
  <div>
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{span:4}"
      :wrapper-col="{span:8}"
    >
      <a-form-item label="优享汇ID" name="id">
        <a-input v-model:value="formState.id" placeholder="系统自动生成" disabled />
      </a-form-item>
      <a-form-item label="选择活动" name="ids" :wrapper-col="{span:20}">
        <!-- <a-select v-model:value="formState.ids" mode="multiple" /> -->
        <a-transfer
          :data-source="mockData"
          :list-style="{
            width: '400px',
            height: '300px',
          }"
          show-search
          :filter-option="filterOption"
          :target-keys="targetKeys"
          :render="item => item.title"
          @change="handleChange"
          @search="handleSearch"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" @click="onSubmit">提交</a-button>
        <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script>
import { defineComponent, reactive, ref, unref, toRaw, onMounted, watch} from 'vue';
import {useRouter} from 'vue-router';
import { message } from 'ant-design-vue';
import {getActivitySearch, add, update, info} from './api';
export default defineComponent({
  setup() {
    const router = useRouter();
    const {query} = router.currentRoute.value;
    const afterSubmit = (res) => {
      res.code == 0 && message.success('提交成功');
      router.back()
    };
    const formRef = ref();
    const formState = reactive({
      id: undefined,
      ids: []
    });
    const rules = {
      id: {
        required: false
      },
      ids: {
        required: true,
        type: 'array',
        message: '请选择活动'
      },
    };

    const onSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          const ids = unref(formState.ids).map(Number)
          const params = {
            id: query.id ? Number(query.id) : undefined,
            ids
          }
          if (query.id) {
            update(params).then(afterSubmit);
          } else {
            add(params).then(afterSubmit);
          }
        })
        .catch(error => {
          console.log('error', error);
        });
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    const mockData = ref([]);
    const targetKeys = ref([]);

    const getMock = (fn) => {
      const mData = [];

      getActivitySearch({keywords:''}).then(res => {
        const list = res?.data || [];
        list.forEach((item) => {
          item.key = `${item.id}`;
          mData.push(item);
        });
        mockData.value = mData;

        fn && fn();
      });
    };

    const filterOption = (inputValue, option) => {
      return option.title.indexOf(inputValue) > -1;
    };

    const handleChange = (keys, direction, moveKeys) => {
      targetKeys.value = keys;
    };

    const handleSearch = (dir, value) => {
      console.log('search:', dir, value);
    };

    watch(targetKeys, v => {
      formState.ids = targetKeys;
      formState.id = query.id;
    });

    onMounted(() => {
      getMock(() => {
        if (query.id) {
          info({id: Number(query.id)}).then(res => {
            var ids = res.data.map(item => `${item.id}`)
            targetKeys.value = ids;
            formState.ids = ids;
          })
        }
      });
    });

    return {
      formRef,
      formState,
      rules,
      onSubmit,
      resetForm,
      mockData,
      targetKeys,
      filterOption,
      handleChange,
      handleSearch,
    };
  },
});
</script>